<?php
namespace app\model;

/**
 * Created by 底片云
 * Desc:大转盘抽奖类
 * User:cbw
 * Date: 2020/11/21
 */
class Lottery
{
    /**
     * Desc:通过fans信息获取粉丝的积分和抽奖次数 更新抽奖机会 以及用户剩余抽奖机会
     * User: cbw
     * Time: 2020/11/19 3:00 下午
     * @param $fans
     * @return array
     */
    public static function checkUserLtNum($fans,$config,$themeid)
    {
        $remnant_num = 0;
        $current_points = 0;
        if ($fans){
            $current_points = $fans['lt_points'];
            $remnant_num = $fans['lt_counter'];
            //用户不存在抽奖机会记录 判断用户的剩余抽奖机会
            $receive_flag = self::getLotteryChanceByUid($fans['uid'],$themeid);
            $no_register_num = $config['fanpaiweibaoming'];
            if ($receive_flag<1 && $no_register_num>=1){
                //不存在抽奖机会记录  系统存在未报名可抽 插入抽奖机会 更新用户剩余抽奖机会
                $insert_data = [
                    'uid'=>$fans['uid'],
                    'type'=>1,
                    'add_key'=>1,
                    'op_num'=>$no_register_num,
                    'themeid'=>$themeid,
                    'today'=>date("Y-m-d",time())
                ];
                $res = self::insertUserRecords($insert_data);
                $new_lt_counter = $remnant_num = $fans['lt_counter']+$no_register_num;
                //用户日志收集
                $log_msg = '获取机会'.$no_register_num.'当前机会'.$new_lt_counter;
                Userdata::addLog($themeid, $fans['uid'], 34, $log_msg);
                $result = self::updateFansInfo($fans['uid'],['lt_counter'=>$new_lt_counter]);
            }
        }
        $data = [
            'lt_counter'=>$remnant_num,
            'lt_points'=>$current_points
        ];
        return $data;
    }

    /**
     * Desc:获取抽奖机会记录数
     * User: cbw
     * Time: 2020/11/25 11:47 上午
     * @param $uid
     * @param $themeid
     * @return int
     */
    public static function getLotteryChanceByUid($uid,$themeid)
    {
        $sql = "select count(*) as cnt from " . tablename(t_lot_record)." where uid='".$uid."' and themeid=".$themeid;
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:获取中奖记录数
     * User: cbw
     * Time: 2020/11/19 8:16 下午
     * @param $uid
     */
    public static function getUserRecords($uid,$themeid,$type=1,$limit=10)
    {
        if ($type==1){
            $condition = " where";
            if ($uid!=0){
                $condition = " where uid='". $uid."' and";
            }
            $sql = "select count(*) as cnt from " . tablename(t_receive) . $condition.
                " themeid=".$themeid."  group by uid";
            $user_flag = intval(db_find($sql)['cnt']);//中奖奖记录数
        }
        if ($type==3){
            $sql = "select count(*) from (select * from " .tablename(t_receive) ." where themeid =".$themeid.
                " group by uid ) as a";
            $user_flag = (int)db_fetchcolumn($sql);
        }
        if ($type==2){
            $sql = "select * from " .tablename(t_receive) ." where themeid =".$themeid.
                " group by uid order by created_at desc limit ".$limit;
            $user_flag = db_select($sql);
        }
        if ($type==4){
            $sql = " select * from ".tablename(t_lottery)." where themeid=$themeid and ltt_showratiio >0 order by ltt_showratiio desc limit ".$limit;
            $user_flag = db_select($sql);
        }
        return $user_flag;
    }

    /**
     * Desc:获取中奖记录 根据用户uid取一次
     * User: cbw
     * Time: 2020/12/1 9:20 上午
     * @param $uid
     * @param $themeid
     * @param int $type
     * @param int $limit
     * @return int
     */
    public static function getRealUsreRecords($uid,$themeid,$type=1,$limit=10)
    {
        $condition = " where";
        if ($uid!=0){
            $condition = " where uid='". $uid."' and";
        }
        $sql = " select * from " . tablename(t_receive) . $condition.
            " themeid=".$themeid."  group by uid";
        $user_flag = db_select($sql);
        return count($user_flag);
    }

    /**
     * Desc:获取当前用户的各种类型的增加抽奖次数的记录
     * User: cbw
     * Time: 2020/11/21 11:01 上午
     * @param $uid
     * @param $type
     * @return int
     */
    public static function getUserRecordsByType($uid,$add_key,$themeid,$check_today=false)
    {
        $condition = " where type=1 and add_key=".$add_key." and uid='".$uid."' and themeid=".$themeid;
        if ($check_today){
            $today = date("Y-m-d",time());
            $condition .= " and today="."'".$today."'";
        }
        $sql = "select count(*) as cnt from ".tablename(t_lot_record). $condition;
        $flags = intval(db_find($sql)['cnt']);
        return $flags;
    }

    /**
     * Desc: 插入抽奖次数的记录
     * User: cbw
     * Time: 2020/11/21 11:38 上午
     * @param $uid
     * @param int $type
     * @param int $add_key
     * @param $themeid
     * @param int $op_num
     * @return bool
     */
    public static function insertUserRecords($data)
    {
        $data['updated_at']=date("Y-m-d H:i:s");
        $res = $insertid = db_insert(t_lot_record,$data);
        if (!$res){
            return false;
        }else{
            return true;
        }
    }

    /**
     * Desc:更新活动粉丝表信息
     * User: cbw
     * Time: 2020/11/19 9:26 下午
     * @param $uid
     * @param $update_data
     * @return bool
     */
    public static function updateFansInfo($uid,$update_data)
    {
        $res = db_update(t_fans,$update_data,['uid'=>$uid]);
        if (!$res){
            return false;
        }else{
            return true;
        }
    }

    /**
     * Desc:操作类型 获取应该增加的抽奖次数
     * User: cbw
     * Time: 2020/11/21 11:09 上午
     * @param $type
     * @param $themeid
     * @param $uid
     * @return int|mixed
     */
    public static function getChanceNumsByType($type,$themeid,$fans)
    {
        $add_chance_num = 0;
        $config =  Theme::getConfig($themeid);
        $chance_limit = $config['fanpailimit'];//抽奖次数上限
        $default_chance = $config['fanpaiweibaoming'];//
        $register_chance = $config['fanpaibaoming'];
        $invite_order_chance = $config['fanpaiyaoqing'];
        $fanpaipengyouquan = $config['fanpaipengyouquan'];//未报名加报名
        $lotteryview_chance = number_format($config['lotterynum']/$config['lotteryview'],2);
        $one_day = $config['fanpai1day'];
        $two_day = $config['fanpai2day'];
        $third_day = $config['fanpai3day'];

        switch ($type){
            case 1:
                $add_chance_num = $default_chance;//未报名
                break;
            case 2:
                $add_chance_num = $register_chance;//报名
                break;
            case 3://转发朋友圈
                $today_flag = self::getUserRecordsByType($fans['uid'],3,$themeid,true);//朋友圈
                $moments = self::getUserRecordsByType($fans['uid'],3,$themeid);
                if ($moments==0){
                    $add_chance_num = $one_day;
                }
                if ($moments==1){
                    $add_chance_num = $two_day;
                }
                if ($moments==2){
                    $add_chance_num = $third_day;
                }
                if (($today_flag>1 && $add_chance_num>0) || ($fanpaipengyouquan==1 && (empty($fans['username']) || empty($fans['mobile'])))){
                    $add_chance_num = 0;
                }

                break;
            case 4:
                $add_chance_num = $invite_order_chance;//邀请好友
                break;
            case 6:
                $add_chance_num = $lotteryview_chance;//好友到访
                break;
            default:
                break;
        }
        return $add_chance_num;
    }

    /**
     * Desc:执行抽奖次数增改操作 记录表以及 用户抽奖剩余次数
     * User: cbw
     * Time: 2020/11/25 5:38 下午
     * @param $l_type
     * @param int $op
     * @param $fans
     * @param $themeid
     */
    public static function formatLotteryDataAndAction($l_type,$op=1,$fans,$themeid)
    {
        $add_chance_num = self::getChanceNumsByType($l_type,$themeid,$fans);
        if ($add_chance_num>0){
            if ($op==1){
                $config =  Theme::getConfig($themeid);
                $insert_data = [
                    'uid'=>$fans['uid'],
                    'type'=>1,
                    'add_key'=>$l_type,
                    'themeid'=>$themeid,
                    'avatar'=>$fans['avatar'],
                    'op_num'=>$add_chance_num,
                    'today'=>date("Y-m-d",time())
                ];

                if (is_int($add_chance_num)){
                    $chance_num = $fans['lt_counter'];
                    $new_chance_num = $chance_num+$add_chance_num;
                }else{
                    $set_lotteryview = $config['lotteryview'];
                    $flag_num = Lottery::getLtFriendNoUsedNum($themeid,$fans['uid']);
                    $new_flag_num = $flag_num+1;
                    if (is_int($new_flag_num/$set_lotteryview)){
                        $chance_num = $fans['lt_counter'];
                        $new_chance_num = $chance_num+$config['lotterynum'];
                    }
                }
                if ($new_chance_num){
                    //用户日志收集
                    $log_msg = '获取机会'.$add_chance_num.'当前机会'.$new_chance_num;
                    Userdata::addLog($themeid, $fans['uid'], 34, $log_msg);
                }

                $res = self::insertUserRecords($insert_data);
                if ($config['fanpailimit']>$chance_num){
                    $result = Lottery::updateFansInfo($fans['uid'],['lt_counter'=>$new_chance_num]);
                }
            }
            if ($op==2){
                $insert_data = [
                    'uid'=>$fans['uid'],
                    'type'=>2,
                    'add_key'=>$l_type,
                    'themeid'=>$themeid,
                    'avatar'=>$fans['avatar'],
                    'op_num'=> (-1* $add_chance_num),
                    'today'=>date("Y-m-d",time())
                ];
                $chance_num = $fans['lt_counter'];
                $new_chance_num = $chance_num-1;
                if ($new_chance_num<=0){
                    $new_chance_num = 0;
                }
                $res = self::insertUserRecords($insert_data);
                $result = Lottery::updateFansInfo($fans['uid'],['lt_counter'=>$new_chance_num]);
            }

        }
    }

    /**
     * Desc:获取中奖记录 真实加虚拟
     * User: cbw
     * Time: 2020/11/23 5:21 下午
     * @param $themeid
     * @param $config
     * @return array|mixed
     */
    public static function getVirtualFlag($themeid,$config)
    {
        $fakelottery = $config['fakelottery'];
        $show_ratiio_total = self::checkShowRatiioItems($themeid);//获取前台展示占比的奖项的数量
        if ($show_ratiio_total>1){
            $real_flag = $show_ratiio_total;
        }else{
            //获取真实用户的一次中奖记录 求总和
            $real_flag = self::getRealUsreRecords(0,$themeid,1);
        }

        if ($real_flag >20){
            if ($show_ratiio_total>1){
                $lt_info = self::getUserRecords(0,$themeid,4);
                $lt_str = '';
                foreach ($lt_info as $key =>$val)
                {
                    $lt_str .= $val['ltt_id'].',';
                }
                $lt_str = rtrim($lt_str,',');
                $flag_list = self::getUserInfoAndLtItemByLttId($lt_str);
            }else{
                $lr_info = self::getUserRecords(0,$themeid,2);
                $lr_str = "";
                foreach ($lr_info as $key =>$val)
                {
                    $lr_str .= $val['lr_id'].',';
                }
                $lr_str = rtrim($lr_str,',');
                $flag_list = self::getUserInfoAndLtItemByLrId($lr_str);
            }
        }else{
            $diff_flag = 20 - $real_flag;
            if ($diff_flag>$fakelottery){$diff_flag=$fakelottery;}
            if ($fakelottery>0){
                $virtual = self::getVirtualUserInfo($diff_flag,$config,$themeid);
                foreach ($virtual as $k =>$v){
                    $virtual[$k]['created_at'] = date("Y-m-d");
                }
            }

            if ($show_ratiio_total>1){
                if ($real_flag>0){
                    $lt_info = self::getUserRecords(0,$themeid,4);
                    $lt_str = '';
                    foreach ($lt_info as $key =>$val)
                    {
                        $lt_str .= $val['ltt_id'].',';
                    }
                    $lt_str = rtrim($lt_str,',');
                    $flag_list = self::getUserInfoAndLtItemByLttId($lt_str);
                    if ($fakelottery){
                        $flag_list = array_merge($virtual,$flag_list);
                    }

                }else{
                    if ($fakelottery){
                        $flag_list = $virtual;
                    }
                }
            }else{
                if ($real_flag>0){
                    $lr_info = self::getUserRecords(0,$themeid,2,$real_flag);
                    $lr_str = "";
                    foreach ($lr_info as $key =>$val)
                    {
                        $lr_str .= $val['lr_id'].',';
                    }
                    $lr_str = rtrim($lr_str,',');
                    $flag_list = self::getUserInfoAndLtItemByLrId($lr_str);
                    if ($fakelottery){
                        $flag_list = array_merge($virtual,$flag_list);
                    }

                }else{
                    if ($fakelottery){
                        $flag_list = $virtual;
                    }
                }
            }
        }
        shuffle($flag_list);
        if (!empty($flag_list)){
            foreach ($flag_list as $k => $v)
            {
                if (!empty($flag_list[$k]['username'])){
                    $flag_list[$k]['username'] = substr_cut_username($v['username']);
                }else{
                    $flag_list[$k]['username'] = $v['nickname'];
                }

                $flag_list[$k]['created_at'] = date("Y-m-d",strtotime($flag_list[$k]['created_at']));
            }
        }
        shuffle($flag_list);
        return $flag_list;
    }

    /**
     * Desc:获取中奖记录信息
     * User: cbw
     * Time: 2020/11/23 8:29 下午
     * @param $uids
     * @return mixed
     */
    public static function getUserInfoAndLtItemByUid($uids)
    {
        $sql = "select a.created_at,b.username,b.avatar,c.ltt_title from ".tablename(t_receive).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".
            " LEFT JOIN ".tablename(t_lottery)." as c on a.ltt_id=c.ltt_id".
            " where a.uid in( ". $uids." ) order by a.created_at desc";
        return db_query($sql);
    }

    /**
     * Desc:通过中奖记录ids获取中奖机会信息以及用户信息
     * User: cbw
     * Time: 2020/11/27 10:14 下午
     * @param $lr_ids
     * @return mixed
     */
    public static function getUserInfoAndLtItemByLrId($lr_ids)
    {
        $sql = "select a.created_at,b.username,b.nickname,b.avatar,c.ltt_title from ".tablename(t_receive).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".
            " LEFT JOIN ".tablename(t_lottery)." as c on a.ltt_id=c.ltt_id".
            " where a.lr_id in( ". $lr_ids." ) and b.nickname is not null and b.avatar is not null and b.nickname <>'' and b.avatar <> '' order by a.created_at desc";
        return db_select($sql);
    }

    /**
     * Desc:通过奖项ids获取中奖记录
     * User: cbw
     * Time: 2020/12/2 11:44 下午
     * @param $ltt_ids
     * @return mixed
     */
    public static function getUserInfoAndLtItemByLttId($ltt_ids)
    {
        $sql = "select a.created_at,b.username,b.nickname,b.avatar,c.ltt_title from ".tablename(t_receive).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".
            " LEFT JOIN ".tablename(t_lottery)." as c on a.ltt_id=c.ltt_id".
            " where a.ltt_id in( ". $ltt_ids." ) and b.nickname <>'' and b.avatar <> '' order by a.created_at desc";
        return db_select($sql);
    }

    /**
     * Desc:获取用户信息 通过uid字符串
     * User: cbw
     * Time: 2020/11/23 4:49 下午
     * @param $uids
     * @return mixed
     */
    public static function getUserInfoByUid($uids)
    {
        $sql = " select username,avatar from ". tablename(t_fans). " where uid in(" . $uids .  ")";
        return db_query($sql);
    }

    /**
     * Desc:获取指定数量的虚拟用户头像和昵称
     * User: cbw
     * Time: 2020/11/23 5:06 下午
     * @param $limit
     * @param $config
     * @return mixed
     */
    public static  function  getVirtualUserInfo($limit,$config,$themeid)
    {
        $res = Fans::getXuniFans($config,$limit,$config['touxiang'],0);
        $show_ratiio_total = self::checkShowRatiioItems($themeid);//获取前台展示占比的奖项的数量
        if ($show_ratiio_total<1){
            foreach ($res as $key =>$val){
                $res[$key]['ltt_title'] = self::getRoundLtItem($themeid,$val['id'])['ltt_title'];
            }
        }else{
            $res = self::getListShowRatiioItems($res,$themeid);
        }

        return $res;
    }

    /**
     * Desc: 虚假用户获取 获取固定的中奖奖项key
     * User: cbw
     * Time: 2020/11/23 8:00 下午
     * @param $themeid
     * @return mixed
     */
    public static function getRoundLtItem($themeid,$id)
    {
        $sql = "select ltt_title from ".tablename(t_lottery)." where ltt_ratiio>1000 and themeid=".$themeid;
        $list = db_select($sql);
        $total = count($list);
        $last_str = (int)substr($id,-1);
        if ($last_str<=$total-1){
            return $list[$last_str];
        }else{
            $key = ceil($last_str % $total);
            return $list[$key];
        }
    }

    /**
     * Desc:虚拟中奖记录根基前台展示占比随机生成
     * User: cbw
     * Time: 2020/12/2 11:21 下午
     * @param $list
     * @param $themeid
     * @return mixed
     */
    public static function getListShowRatiioItems($list,$themeid)
    {
        $max_num = count($list);
        $eq_show_list = self::getShowRatiioItems($themeid);
        $eq_show_total = count($eq_show_list);
        if ($eq_show_total>1){
            //存在展示占比奖项
            $show_items = [];
            $show_items_num = 0;
            foreach ($eq_show_list as $k => $val)
            {
                $show_item = [];
                $show_item['ltt_title'] = $val['ltt_title'];
                $show_item['total'] = (int)ceil(($val['ltt_showratiio']/10000)*count($list));
                $show_items_num += $show_item['total'];
                array_push($show_items,$show_item);
            }

            if ($show_items_num < $max_num){
                foreach ($show_items as $key =>$v){
                    if (($v['total']+1)<$max_num && $show_items_num < $max_num){
                        $show_items[$key]['total'] +=1;
                        $show_items_num+=1;
                    }
                }
            }
            $diff = $max_num-$show_items_num;
            $round_key = round(0,$eq_show_total-1);
            $show_items[$round_key]['total'] +=$diff;

            $first_arr = [];
            foreach ($list as $kk => $vv)
            {
                $temp_arr = [];
                $temp_arr['key']=$kk;
                array_push($first_arr,$temp_arr);
            }

            foreach ($show_items as $dd =>$ff)
            {
                for ($i=1;$i<=$ff['total'];$i++)
                {
                    $first_round = (int)round(0,count($first_arr)-1);
                    $temp_key = $first_arr[$first_round]['key'];
                    $list[$temp_key]['ltt_title'] = $ff['ltt_title'];
                    array_splice($first_arr,$first_round,1);
                }
            }
            shuffle($list);
        }
        return $list;
    }

    /**
     * Desc:获取抽奖机会 以及用户信息 适用列表和搜索
     * User: cbw
     * Time: 2020/11/27 10:13 下午
     * @param $themeid
     * @param string $nickname
     * @param string $start_day
     * @param string $end_day
     * @param $page_start
     * @param $page_size
     * @return mixed
     */
    public static function getDefaultOrSearchChanceList($themeid,$nickname='',$start_day='',$end_day='',$page_start,$page_size)
    {
        $condition = " where a.themeid=$themeid order by  a.created_at desc limit ".$page_start.",".$page_size;
        if ($nickname){
            $condition = " where a.themeid=$themeid and b.nickname like '".$nickname."' order by  a.created_at desc limit ".$page_start.",".$page_size;
        }
        if ($start_day && $end_day){
            $condition = " where a.themeid=".$themeid." and a.created_at between '".$start_day."' and '".$end_day."' order by a.created_at desc limit ".$page_start.",".$page_size;
        }
        $sql = "select a.lnr_id,a.created_at,a.type,a.add_key,a.op_num,b.username,b.avatar,b.nickname,b.mobile from ".tablename(t_lot_record).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:通过抽奖机会id 获取抽奖机会详情
     * User: cbw
     * Time: 2020/11/27 10:13 下午
     * @param $id
     * @return mixed
     */
    public static function getLotteryChanceInfo($id)
    {
        $res = db_get(t_lot_record,['lnr_id'=>$id]);
        return $res;
    }

    /**
     * Desc:获取中奖记录 关联奖项 粉丝 适用列表和搜索
     * User: cbw
     * Time: 2020/11/27 10:12 下午
     * @param $themeid
     * @param string $nickname
     * @param string $start_day
     * @param string $end_day
     * @param $page_start
     * @param $page_size
     * @return mixed
     */
    public static function getLotteryReceive($themeid,$nickname='',$start_day='',$end_day='',$page_start,$page_size)
    {
        $condition = " where a.themeid=$themeid order by  a.created_at desc limit ".$page_start.",".$page_size;
        if ($nickname){
            $condition = " where a.themeid=$themeid and b.nickname like '".$nickname."' order by  a.created_at desc limit ".$page_start.",".$page_size;
        }
        if ($start_day && $end_day){
            $condition = " where a.themeid=".$themeid." and a.created_at between '".$start_day."' and '".$end_day."' order by a.created_at desc limit ".$page_start.",".$page_size;
        }
        $sql = "select a.created_at,a.lr_id,a.ltt_id,a.receive_key,a.receive_todo_num,a.receive_remain_num,a.status,b.username,b.avatar,b.nickname,b.mobile,c.ltt_title,c.ltp_name,c.ltp_img from ".tablename(t_receive).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".
            " LEFT JOIN ".tablename(t_lottery)." as c on a.ltt_id=c.ltt_id".$condition;
        return db_select($sql);
    }

    /**
     * Desc:通过中奖记录id获取中奖记录信息
     * User: cbw
     * Time: 2020/11/27 10:11 下午
     * @param $id
     * @return mixed
     */
    public static function getLtRecordByLrId($id)
    {
        $res = db_get(t_receive,['lr_id'=>$id]);
        return $res;
    }

    /**
     * Desc:更新中奖记录信息
     * User: cbw
     * Time: 2020/11/27 10:11 下午
     * @param $id
     * @param $data
     * @return mixed
     */
    public static function updateLtRecordByLrId($id,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = db_update(t_receive,$data,['lr_id'=>$id]);
        return $res;
    }

    /**
     * Desc:插入中奖记录
     * User: cbw
     * Time: 2020/11/27 10:10 下午
     * @param $data
     * @return mixed
     */
    public static function insertLtRerord($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(t_receive,$data);
        return $res;
    }

    /**
     * Desc:获取用户指定类型的中奖记录
     * User: cbw
     * Time: 2020/11/30 1:06 上午
     * @param $receive_key
     * @param $status
     * @param $uid
     * @return mixed
     */
    public static function getLastLtRecordInfoByUid($receive_key,$id)
    {
        $sql = " select * from " . tablename(t_receive) ." where receive_key=$receive_key and lr_id=$id";
        return db_select($sql);
    }

    /**
     * Desc:通过keu uid 获取用户指定的中奖记录
     * User: cbw
     * Time: 2020/12/1 11:02 下午
     * @param $receive_key
     * @param $status
     * @param $uid
     * @return mixed
     */
    public static function getLastLtRecordInfo($receive_key,$status,$uid)
    {
        $sql = " select * from " . tablename(t_receive) ."where receive_key=$receive_key and status=$status and uid='{$uid}'".
            " order by created_at desc limit 1";
        return db_find($sql);
    }

    /**
     * Desc:获取用户是否存在查询的奖项中奖记录
     * User: cbw
     * Time: 2020/12/1 9:06 上午
     * @param $uid
     * @param $themeid
     * @param $ltt_id
     * @return int
     */
    public static function checkUserHasRecordFlag($uid,$themeid,$ltt_id)
    {
        $sql = "select count(*) as cnt from " . tablename(t_receive)." where uid='".$uid."' and themeid=".$themeid." and ltt_id=".$ltt_id;
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:获取奖项类型的数量
     * User: cbw
     * Time: 2020/12/1 10:17 上午
     * @param $themeid
     * @param int $item_type
     * @return int
     */
    public static function getLtItemTotal($themeid,$item_type=0)
    {
        if (!$item_type){
            $sql = "select count(*) as cnt from " . tablename(t_lottery)." where themeid=".$themeid;
        }else{
            $sql = "select count(*) as cnt from " . tablename(t_lottery)." where themeid=".$themeid." and it_type=".$item_type;
        }
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:获取用户的中奖记录
     * User: cbw
     * Time: 2020/12/1 11:38 上午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getUserRecordListByUid($themeid,$uid)
    {
        $sql = "select a.*,b.ltt_title,b.ltp_name,b.ltp_img,b.it_type from ".tablename(t_receive)." as a left join ".tablename(t_lottery)." as b on a.ltt_id = b.ltt_id".
            " where a.themeid=$themeid and a.uid='{$uid}'";
        $res  = db_select($sql);
        return $res;
    }

    /**
     * Desc:获取用户的已中奖中的必中奖条件
     * User: cbw
     * Time: 2020/12/1 11:38 上午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getUserRecordSql($themeid,$uid)
    {
        $sql = "select b.ltt_id from ".tablename(t_receive)." as a left join ".tablename(t_lottery)." as b on a.ltt_id = b.ltt_id".
            " where a.themeid=$themeid and a.uid='{$uid}' and b.it_type=3";
        $res  = db_select($sql);
        if (!empty($res)){
            foreach ($res as $index=>$item ){
                if ($index==0){
                    $ids = $item['ltt_id'];
                }else{
                    $ids = $ids . "," . $item['ltt_id'];
                }
            }
            if (count($res)==1){
                $result = " and ltt_id <> " . $ids;
            }else{
                $result = " and ltt_id not in (" . $ids .")";
            }
        }
        return $result;
    }

    /**
     * Desc:获取展示比例 降序 list
     * User: cbw
     * Time: 2020/12/2 9:16 下午
     * @param $themeid
     * @return mixed
     */
    public static function getShowRatiioItems($themeid)
    {
        $sql = " select * from ".tablename(t_lottery)." where themeid=$themeid and ltt_showratiio >0 order by ltt_showratiio desc";
        $res = db_select($sql);
        return $res;
    }

    /**
     * Desc:判断展示占比大于0 的奖项数量
     * User: cbw
     * Time: 2020/12/2 9:39 下午
     * @param $themeid
     * @return mixed
     */
    public static function checkShowRatiioItems($themeid)
    {
        $sql = " select count(*) as cnt from " .tablename(t_lottery)." where themeid=$themeid and ltt_showratiio >0";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取用户可用的抽奖攻略
     * User: cbw
     * Time: 2020/12/16 1:25 下午
     * @param $fans
     * @param $themeid
     * @param $config
     * @return array
     */
    public static function getUserLotteryOpList($lt_counter_now,$fans,$themeid,$config)
    {
        global $_G, $_P;
        $list = [];
        $btnTxt1 = '已完成';
        $status1 = 1;
        $btnTxt2 = '去完成';
        $status2 = 2;
        $btnTxt3 = '到达上限';
        $status3 = 3;

        $add_chance_num = 0;
        $fanpaipengyouquan = $config['fanpaipengyouquan'];//未报名加报名
        $one_day = $config['fanpai1day'];
        $two_day = $config['fanpai2day'];
        $third_day = $config['fanpai3day'];
        $pyqall = $one_day+$two_day+$third_day;
        if ($pyqall>0){
            $today_flag = self::getUserRecordsByType($fans['uid'],3,$themeid,true);//朋友圈今日记录
            $moments = self::getUserRecordsByType($fans['uid'],3,$themeid);
            if ($moments==0){
                $add_chance_num = $one_day;
            }
            if ($moments==1){
                $add_chance_num = $two_day;
            }
            if ($moments==2){
                $add_chance_num = $third_day;
            }
            if (($today_flag>1 && $add_chance_num>0) || ($fanpaipengyouquan==1 && (empty($fans['username']) || empty($fans['mobile'])))){
                $add_chance_num = 0;
            }
            $detail="将链接分享到朋友圈";
            if ($one_day>0){
                $detail.="，第1天增加". $one_day. "次抽奖机会";
            }
            if ($two_day>0){
                $detail.="，第2天增加". $two_day. "次机会";
            }
            if ($third_day>0){
                $detail.="，第3天增加". $third_day. "次机会";
            }
        }

        if ($lt_counter_now>=$config['fanpailimit']){
            //达到上限
            if ($config['fanpaibaoming']>0){
                $temp_1 = ['title'=>'下单抢购','detail'=>'您自己下单抢购增加'. $config['fanpaibaoming']. '次抽奖机会','key'=>'fanpaibaoming','num'=>$config['fanpaibaoming'],'btnTxt'=>$btnTxt3,'status'=>$status3];
            }
            if ($config['fanpaiyaoqing']>0){
                $temp_2 = ['title'=>'好友抢购','detail'=>'好友通过您分享的链接下单抢购，您增加'. $config['fanpaiyaoqing']. '次抽奖机会','key'=>'fanpaiyaoqing','num'=>$config['fanpaiyaoqing'],'btnTxt'=>$btnTxt3,'status'=>$status3];
            }
            //分享朋友圈
            if ($pyqall>0) {
                    $temp_3 = ['title' => '分享朋友圈', 'detail'=>$detail, 'key' => 'fanpaipengyouquan', 'num' => $pyqall,  'btnTxt' => $btnTxt3, 'status' => $status3];
            }
            if ($config['lotteryview']>0 && $config['lotterynum']>0){
                $temp_4 = ['title'=>'好友到访','detail'=>$config['lotteryview'].'位好友到访增加','key'=>'lotteryview','num'=>$config['lotterynum'],'btnTxt'=>$btnTxt3,'status'=>$status3];
            }
        }else{
            //判断用户是否报名
            if ($config['fanpaibaoming']>0){
                $themyrecord = Record::getLastGroupByUid($_G['member']['uid'],$_P['themeid']);
                if (empty($themyrecord)){
                    $temp_1 = ['title'=>'下单抢购','detail'=>'您自己下单抢购增加'. $config['fanpaibaoming']. '次抽奖机会','key'=>'fanpaibaoming','num'=>$config['fanpaibaoming'],'btnTxt'=>$btnTxt2,'status'=>$status2];
                }else{
                    $temp_1 = ['title'=>'下单抢购','detail'=>'您自己下单抢购增加'. $config['fanpaibaoming']. '次抽奖机会','key'=>'fanpaibaoming','num'=>$config['fanpaibaoming'],'btnTxt'=>$btnTxt1,'status'=>$status1];
                }
            }
            //直接添加邀请好友报名加抽次数
            if ($config['fanpaiyaoqing']>0){
                $temp_2 = ['title'=>'好友抢购','detail'=>'好友通过您分享的链接下单抢购，您增加'. $config['fanpaiyaoqing']. '次抽奖机会','key'=>'fanpaiyaoqing','num'=>$config['fanpaiyaoqing'],'btnTxt'=>$btnTxt2,'status'=>$status2];
            }
            //分享朋友圈
            if ($pyqall>0) {
                if ($moments <= 2) {
                    if ($today_flag >= 1 && $add_chance_num > 0) {
                        $title = '分享朋友圈今日已完成';
                        $status = $status1;
                        $btnTxt = $btnTxt1;
                    }
                    if ($today_flag < 1 && $add_chance_num > 0) {
                        $title = '分享到朋友圈';
                        $status = $status2;
                        $btnTxt = $btnTxt2;
                    }
                    if ($title) {
                        $temp_3 = ['title' => $title, 'detail' => $detail, 'key' => 'fanpaipengyouquan', 'num' => $pyqall, 'btnTxt' => $btnTxt, 'status' => $status,'receive_key'=>2];
                    } else {
                        $temp_3 = ['title' => '分享朋友圈', 'detail' => $detail, 'key' => 'fanpaipengyouquan', 'num' => $pyqall, 'btnTxt' => $btnTxt1, 'status' => $status1,'receive_key'=>2];
                    }
                } else {
                    $temp_3 = ['title' => '分享朋友圈', 'detail' => $detail, 'key' => 'fanpaipengyouquan', 'num' => $pyqall, 'btnTxt' => $btnTxt1, 'status' => $status1,'receive_key'=>2];
                }
            }
            //好友到访
            if ($config['lotteryview']>0 && $config['lotterynum']>0){
                $temp_4 = ['title'=>'好友到访','detail'=>"每".$config['lotteryview'].'位好友通过您分享的链接进入活动，您增加'.$config['lotterynum']. '次抽奖机会' ,'key'=>'lotteryview','num'=>$config['lotterynum'],'btnTxt'=>$btnTxt2,'status'=>$status2];
            }
        }
        if ($temp_1){
            array_push($list,$temp_1);
        }
        if ($temp_2){
            array_push($list,$temp_2);
        }
        if ($temp_3){
            array_push($list,$temp_3);
        }
        if ($temp_4){
            array_push($list,$temp_4);
        }
        return $list;
    }

    /**
     * Desc:获取抽奖机会上限以及提示语
     * User: cbw
     * Time: 2020/12/16 10:22 上午
     * @param $config
     * @return array
     */
    public static function getLotteryMaxAndTips($lt_counter_now,$config)
    {
        return ['tips'=>'您已获得'. $lt_counter_now. '次抽奖机会，最高可获得'.$config['fanpailimit'].'次','max'=>$config['fanpailimit']];
    }

    /**
     * Desc:获取用户的抽奖增加和减少的记录
     * User: cbw
     * Time: 2020/12/16 1:33 下午
     * @param $themeid
     * @param $uid
     * @param int $limit
     * @return mixed
     */
    public static function getLotteryOpFlagByUid($themeid,$uid,$limit=20)
    {
        $sql = "select * from ".tablename(t_lot_record)." where uid = '{$uid}' and themeid=$themeid order by created_at desc LIMIT $limit";
        $res = db_select($sql);
        return $res;
    }

    /**
     * Desc:获取用户未使用的好友到访记录数
     * User: cbw
     * Time: 2020/12/16 4:19 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getLtFriendNoUsedNum($themeid,$uid,$add_key=6,$type=1)
    {
        $sql = " select count(*) as cnt from ".tablename(t_lot_record)." where themeid=$themeid and type=$type and uid='{$uid}' and add_key=$add_key";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取指定数量的未使用的好友到访记录
     * User: cbw
     * Time: 2020/12/16 4:31 下午
     * @param $themeid
     * @param $uid
     * @param $limit
     * @return mixed
     */
    public static function getLtFriendNoUesdList($themeid,$uid,$limit)
    {
        $sql = " select * from ".tablename(t_lot_friend_flag)." where themeid=$themeid and uid='{$uid}' and type='no' order by created_at asc limit $limit";
        return db_find($sql);
    }

    /**
     * Desc:更新好友到访信息
     * User: cbw
     * Time: 2020/12/16 4:40 下午
     * @param $condition
     * @return mixed
     */
    public static function updateFriendNoUsed($condition)
    {
        $sql = " update ".tablename(t_lot_friend_flag)." set type='yes' where ".$condition;
        return db_find($sql);
    }

    /**
     * Desc: 中奖后领奖动作
     * User: cbw
     * Time: 2020/12/16 6:58 下午
     * @param $op_type 操作类型 'new_friend'
     * @param $fans fans
     * @param $lr_id 中奖记录id
     */
    public static function opReceiveRemainNum($op_type,$fans,$lr_id)
    {
        $key = getShareReceiveCode($op_type);
        if ($key){
            if ($lr_id){
                //判断中奖记录id  更新对应的中奖记录的操作
                $res = Lottery::getLastLtRecordInfoByUid($key,$lr_id);
            }else{
                //判断用户最近是否有中奖记录  存在对应类型 未领取 时间倒序 最后一条
                $res = Lottery::getLastLtRecordInfo($key,2,$fans['uid']);
            }
            if ($res){
                $lr_id = $res['lr_id'];
                $receive_remain_num = $res['receive_remain_num'];
                $new_receive_remain_num = $receive_remain_num-1;
                $new_receive_remain_num = $new_receive_remain_num<0?0:$new_receive_remain_num;
                $data = [
                    'receive_remain_num'=>$new_receive_remain_num
                ];
                if ($new_receive_remain_num<=0){
                    $data['status'] = 1;
                }
                $result = db_update(t_receive,$data,['lr_id'=>$lr_id]);
            }
        }
    }
}